package cn.bonoon.controllers.fmm;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.plugins.AccountProxyService;
import cn.bonoon.handler.LoginUserDetailsService;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.security.LogonUserProxyable;
import cn.bonoon.kernel.web.controllers.AbstractController;
import cn.bonoon.kernel.web.models.JsonResult;

/**
 * 用来做账号代管的
 * 还要支持另外一种，就是一个账号，可以管理下面几个账号；
 * 登录上去之后，就可以看到自己代管的几个账号，点击一个账号就可以进入这个账号
 * 
 * @author jackson
 *
 */
@Controller
@RequestMapping("s/sys/account/proxy")
public class AccountProxyController extends AbstractController{
	
	@Autowired
	private AccountProxyService accountProxyService;
	@Autowired
	private LoginUserDetailsService loginUserService;
	
	@ResponseBody
	@RequestMapping(value = "in.do", method = POST)
	public Object index(
			@RequestParam("_00_0") String loginName, 
			@RequestParam("_00_1") String proxyPwd){
		try{
			LogonUserProxyable user = user(LogonUserProxyable.class);
			if(null != user){
				LogonUser target = loginUserService.loadUser(loginName);
				accountProxyService.validate(user, proxyPwd, target);
				user.proxy(target);
				return JsonResult.result();
			}
			
			throw new Exception("不能代理账号：" + loginName);
		}catch (Exception e) {
			return JsonResult.error(e);
		}
	}

	@ResponseBody
	@RequestMapping(value = "out.do", method = POST)
	public Object index(){
		try{
			LogonUserProxyable user = user(LogonUserProxyable.class);
			if(null != user){
				user.reset();
				return JsonResult.result();
			}

			throw new Exception("退出代理失败！");
		}catch (Exception e) {
			return JsonResult.error(e);
		}
	}
}
